import * as React from 'react'
import { Toast, Modal } from 'antd-mobile'
import { Gird, Item, Radio, Icon, Button, NavBar, PayInput } from 'components'
import './index.less'
import { post } from '../../utils'
import { browser, wxPay } from 'muka'

export default class SelectPay extends React.Component<any, any> {
    public state = {
        payType: 'wxPay',
        showPayInput: false,
        beanPayOrderId: null,
        goodsPayOrderId: null,
    }
    public render() {
        const { payType, showPayInput } = this.state
        const { order } = this.props
        let data: any = order
        // if (match.params.id === '5') {
        //     data = order
        // }
        const search: any = browser.search
        return (
            <div className="select_pay">
                <NavBar
                    className="select_pay_header"
                    title="收银台"
                    fixed={true}
                />
                <div style={{ padding: '0.5rem 0.5rem 0.4rem 0.5rem' }}>
                    <Gird style={{ padding: 0, margin: 0 }}>
                        <Item
                            className="select_pay_item"
                            title={
                                <div className="flex">
                                    <Icon type="wxPay" className="select_pay_item__icon flex_justify" />
                                    <div>
                                        <div className="select_pay_item__title">微信支付</div>
                                        <div className="select_pay_item__label">微信安全支付</div>
                                    </div>
                                </div>
                            }
                            value={<Radio checked={payType === 'wxPay'} onChange={this.handleType.bind(this, 'wxPay')} />}
                        />
                        {/* <Item
                            className="select_pay_item"
                            title={
                                <div className="flex">
                                    <Icon type="aliPay" className="select_pay_item__icon flex_justify" style={{ color: '#3c8bf6' }} />
                                    <div>
                                        <div className="select_pay_item__title">支付宝支付</div>
                                        <div className="select_pay_item__label">支付宝安全支付</div>
                                    </div>
                                </div>
                            }
                            value={<Radio checked={payType === 'aliPay'} onChange={this.handleType.bind(this, 'aliPay')} />}
                        /> */}
                        {
                            search.id !== '6' &&
                            <Item
                                className="select_pay_item"
                                title={
                                    <div className="flex">
                                        <Icon type="purse" className="select_pay_item__icon flex_justify" style={{ color: '#fa4700' }} />
                                        <div>
                                            <div className="select_pay_item__title">账户余额支付<Button className="btn">推荐</Button></div>
                                            <div className="select_pay_item__label">有钱才是硬道理</div>
                                        </div>
                                    </div>
                                }
                                value={<Radio checked={payType === 'balance'} onChange={this.handleType.bind(this, 'balance')} />}
                            />
                        }
                    </Gird>
                </div>
                <Button className="select_pay__footer" onClick={this.handlePay}>{this.getTypeLabel(payType)}支付{data.price ? Number(data.price).toFixed(2) : '0.00'}元</Button>
                <Modal
                    visible={showPayInput}
                    popup={true}
                    animationType="slide-up"
                    onClose={() => {this.setState({showPayInput: false})}}
                >
                    <div className="select_pay_payPswVerify">
                        <PayInput autoFoucs={true} pwdHide={false} onComplete={(val: string) => { this.handleVerifyPayPsw(val) }} />       
                    </div>                 
                </Modal>
            </div>
        )
    }

    private handleVerifyPayPsw = (val: string) => {
        Toast.info('验证中...', 0)
        const { userInfo } = this.props
        post('usersapi/userPayPwdGet', {
            userId: userInfo.id,
            paypwd: val
        }).then((data: any) => {
            if (data.code === 0) {
                Toast.fail('密码错误')
            }
            if (data.code === 2) {
                Toast.hide()
                this.handleSubmitOrder()                
            }
            return
        }).catch(() => {
            Toast.hide()
        })
    }
    private handleSubmitOrder = () => {
        const search: any = browser.search
        const { beanPayOrderId, goodsPayOrderId } = this.state
        const { userInfo, history } = this.props
        Toast.info('支付中...')
        // 购买恒豆 余额支付
        if (search.id === '5') {
            post('payapi/beanBalancePay', {
                id: beanPayOrderId,
                userId: userInfo.id,
            }).then(() => {
                Toast.info('支付成功！', 2, () => { history.go(-2) })
            }).catch(() => {
                Toast.info('支付失败！', 1.5)
            })
        }
        // 购买商品 余额支付
        if (search.id === '3') {
            post('payapi/balancePay', {
                id: goodsPayOrderId,
                userId: userInfo.id
            }).then((data: any) => {
                Toast.hide()
                history.push(`/payFinish/${goodsPayOrderId}/3`)
            })
        }
        
    }
    private handleType(type: string) {
        this.setState({
            payType: type
        })
    }

    private getTypeLabel = (status: string) => {
        switch (status) {
            case 'aliPay': {
                return '支付宝'
            }
            case 'balance': {
                return '余额'
            }
            default: return '微信'
        }
    }

    private handlePay = () => {
        const { payType } = this.state
        const { userInfo, order } = this.props
        const search: any = browser.search
        // 商品购买
        if (search.id === '3') {
            this.getTypePay(search.orderId)
            return
        }
        // 恒豆支付
        if (search.id === '5') {
            const { wxInfo, history } = this.props
            post('beanapi/beanAddOrder', {
                ...order,
                userId: userInfo.id,
                pay_type: payType
            }).then((data: any) => {
                if (payType === 'wxPay') {
                    Toast.loading('', 0)
                    post('payapi/wxpayBean', {
                        id: data,
                        userId: userInfo.id,
                        wx_openid: wxInfo.wx_openid
                    }).then((result: any) => {
                        wxPay({
                            config: result.jsApiParameters,
                            cbConfig: {
                                ok: () => { Toast.info('支付成功！', 2, () => { history.go(-2) }) },
                                fail: () => { Toast.info('支付已取消,即将返回购买页面', 2, () => { history.go(-2) }) },
                                other: () => { Toast.info('支付发生未知错误,即将返回购买页面', 2, () => { history.go(-2) }) }
                            }
                        })
                    })
                } else if (payType === 'balance') {
                    this.setState({
                        showPayInput: true,
                        beanPayOrderId: data,
                    })
                }
            })
            return
        }
        // 充值
        if (search.id === '6') {
            const { wxInfo, history } = this.props
            post('payapi/wxpayRecharge', {
                price: order.price,
                wx_openid: wxInfo.wx_openid
            }).then((data: any) => {
                wxPay({
                    config: data.jsApiParameters,
                    cbConfig: {
                        ok: () => { Toast.info('充值成功！', 2, () => { history.goBack(-2) }) },
                        fail: () => { alert('支付发生错误') },
                        other: () => { alert('支付遇到未知错误') }
                    }
                })
            })
        }
    }

    private getTypePay(orderId: string) {
        const { payType } = this.state
        const { userInfo, history, wxInfo } = this.props
        switch (payType) {
            case 'wxPay': {
                return post('payapi/wxpay', {
                    id: orderId,
                    userId: userInfo.id,
                    wx_openid: wxInfo.wx_openid
                }).then((data: any) => {
                    wxPay({
                        config: data.jsApiParameters,
                        cbConfig: {
                            ok: () => { history.push(`/payFinish/${orderId}`) },
                            cancel: () => { const { SET_USER_ORDER_INDEX } = this.props; SET_USER_ORDER_INDEX(2); history.push(`/My/myOrder/`) },
                            fail: () => { alert('支付发生错误') },
                            other: () => { alert('支付遇到未知错误') }
                        }
                    })
                })
            }
            case 'balance': {
                this.setState({
                    showPayInput: true,
                    goodsPayOrderId: orderId,
                })
                break
            }
            default: return Promise.resolve({})
        }
    }
}